var $tbody = $("#sample-table-1 tbody");
var allStation = [];
var allAdminRoles = [];

jQuery(function ($) {
    $('.date-picker').datepicker({autoclose: true}).next().on(ace.click_event, function () {
        $(this).prev().focus();
    });
});
var allStation = [];
var nowdate = new Date();
var oneweekdate = new Date(nowdate-7*24*3600*1000);
// $("#startdate").val(beginDate(oneweekdate));
// $("#enddate").val(endDate(nowdate));

function beginDate(date) {
    return endDate(date);
};

function endDate(date) {
    return date.getFullYear() + "-" + ("0" + (date.getMonth() + 1)).slice(-2) + "-" + ("0" + date.getDate()).slice(-2);
};
// 初始化table
$("#joke_table").bootstrapTable({
    // 'url': '../serviceType/findAll',
    'url': '/news/jokeMessage/getJokeMessage',
    'toolbar': $('div[data-name="btnCtl"]'),
    'queryParams': queryParams,
    'cache':false,
    'sidePagination': 'server',
    'toolbarAlign': 'right',
    'undefinedText': '-',
    'striped': true,
    'pagination': true,
    'sortable': true, //是否启用排序
    'sortOrder': "asc", //排序方式
    'pageSize': globalPageSize,
    'pageList': [],
    'clickToSelect': true,
    'singleSelect': true,
    'smartDisplay': true,
    'ajaxOptions':{
        headers: {"Authorization": localStorage.token}
    },
    'responseHandler': function (resb) {
        return {
            'total': resb.data.totalRows,
            'rows': resb.data.jokeRows
        }
    },
    'onCheck': function() {
        $("button[data-target='#reportModal'], button[data-target='#deleteModal']").removeAttr("disabled");
    },
    'onUncheck': function() {
        $("button[data-target='#reportModal'], button[data-target='#deleteModal']").attr("disabled", 'true');
    },
    'onPageChange': function() {
        if($("#yuanfen_table").bootstrapTable('getSelections')[0]){
            $("#yuanfen_table").bootstrapTable('uncheckBy', {
                field: 'typeId',
                values: [$("#yuanfen_table").bootstrapTable('getSelections')[0].typeId]
            });
        }

    },
    'columns': [{
        'checkbox': true,
        // 'class': 'hide'
    },
        {
            'field': 'jokeMsgId',
            'title': '笑话ID',
            'width':100,
            'align': 'center',
            'class': 'hide'
        },{
            'field': 'userName',
            'title': '用户名',
            'width':100,
            'align': 'center',
            'class':'hide'
        },{
            'field': 'jokeType',
            'title': '笑话类型',
            'width':100,
            'align': 'center',
            'formatter': function (jokeType) {
                var obj = {'0':'纯文本','1':'文本+图片','2':'文本+视频'};
                return obj[jokeType];
            }
        },{
            'field': 'jokeContent',
            'title': '笑话内容',
            'align': 'center',
            'width':315
        },{
            'field': 'jokeImgUrl',
            'title': '图片地址',
            'width':225,
            'align': 'center'

        },{
            'field': 'jokeVideoUrl',
            'title': '视频地址',
            'width':225,
            'align': 'center'

        },{
            'field': 'jokeStatus',
            'title': '状态',
            'width':75,
            'align': 'center',
            'formatter': function (jokeStatus) {
                var obj = {'0':'有效','1':'无效'};
                return obj[jokeStatus];
            }
        },{
            'field': 'likeCount',
            'title': '点赞数',
            'width':75,
            'align': 'center'

        },{
            'field': 'commentCount',
            'title': '评论数',
            'width':75,
            'align': 'center'
        },{
            'field': 'shareCount',
            'title': '分享数',
            'width':75,
            'align': 'center'
        },{
            'field': 'createDate',
            'title': '创建日期',
            'width':150,
            'align': 'center',
            'sortable': true
        }

    ]
});
// });

//请求服务数据时所传参数
function queryParams(params){
    return {
        'jokeContent': $('#jokeContent').val(),
        'jokeType' : $('#jokeType').val(),
        'jokeStatus' : $('#jokeStatus').val(),
        'createDateS': $('#startdate').val(),
        'createDateE' : $('#enddate').val(),
        msgSize : params.limit, //每一页的数据行数，默认是上面设置的15(pageSize)
        pageNo : params.offset/params.limit+1 //当前页面,默认是上面设置的1(pageNumber)
    }
}

/**
 * 举报的帖子查询ajax
 * @param name 请求查询的服务人员
 */
function reportQuery(reason,createDateS,createDateE) {
    if (($("#inputStation").val() == '')) {
        $('#report_table').bootstrapTable('refreshOptions', {pageNumber: 1, pageSize: globalPageSize});
    } else {
        $.ajaxSetup({cache:false});
        $.ajax({
            type: "GET",
            url: "/news/jokeMessage/getJokeMessage?msgContent="+$('#contentName').val()+"&msgType="+$('.selectClassify').val()+"&createDateS="+$('#startdate').val()+"&createDateE="+$('#enddate').val()+"&offset=0&limit="+globalPageSize,
            // data: {
            //     'forumReportReason': reason,
            //     'createDateS':createDateS,
            //     'createDateE':createDateE,
            //     'offset': 0,
            //     'limit': globalPageSize
            // },
            // dataType: 'json',
            // 'sidePagination': 'server',

            success: function (resb) {
                if (resb.data.length != 0) {
                    $("#joke_table").bootstrapTable('load', {'total': resb.data.total, 'rows': resb.data.rows});
                } else {
                    $("#joke_table").bootstrapTable('removeAll');
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            }
        });
    }
    return false;
}

/**
 * 笑话搜索的ajax
 */
function jokeQuery() {
    $.ajaxSetup({cache:false});
    $.ajax({
        type: "GET",
        url: "/news/jokeMessage/getJokeMessage?jokeContent="+$('#jokeContent').val()+"&jokeType="+$('#jokeType').val()+"&jokeStatus="+$('#jokeStatus').val()+"&createDateS="+$('#startdate').val()+"&createDateE="+$('#enddate').val()+"&pageNo=1&msgSize="+globalPageSize,
        // data: {
        //     'forumReportReason': reason,
        //     'createDateS':createDateS,
        //     'createDateE':createDateE,
        //     'offset': 0,
        //     'limit': globalPageSize
        // },
        // dataType: 'json',
        // 'sidePagination': 'server',
        beforeSend: function (request) {
            request.setRequestHeader("Authorization", localStorage.token);
        },
        success: function (resb) {
            if (resb.data.length != 0) {
                $("#joke_table").bootstrapTable('load', {'total': resb.data.totalRows, 'rows': resb.data.jokeRows});
            } else {
                $("#joke_table").bootstrapTable('removeAll');
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        }
    });
}


/**
 * 举报原因查询ajax
 * @param forumMsgId 请求查询的t帖子ID
 */
function getReason(forumMsgId) {
    $("#reportReason_table").bootstrapTable('destroy');
    $("#reportReason_table").bootstrapTable({
        // 'url': '../serviceType/findAll',
        'url': '/community/forumreport/findForumreportByMsgId?forumMsgId='+forumMsgId,
        'toolbar': $('div[data-name="btnCtl"]'),
        // 'queryParams': queryParams,
        'cache':false,
        // 'sidePagination': 'server',
        'toolbarAlign': 'right',
        'undefinedText': '-',
        'striped': true,
        'pagination': true,
        'sortable': true, //是否启用排序
        'sortOrder': "asc", //排序方式
        // 'pageSize': globalPageSize,
        'pageList': [],
        'clickToSelect': true,
        'singleSelect': true,
        'smartDisplay': true,
        'ajaxOptions':{
            headers: {"Authorization": localStorage.userId}
        },
        'columns': [{
            'checkbox': true,
            'class': 'hide'
        },
            {
                'field': 'reportedUserId',
                'title': '被举报用户ID',
                'width':200,
                'align': 'center',
                'class': 'hide'
            },{
                'field': 'forumReportReason',
                'title': '举报原因',
                'width':250,
                'align': 'center'

            },{
                'field': 'createDate',
                'title': '创建日期',
                'width':200,
                'align': 'center',
                'sortable': true
            }
        ]
    });
};



/**
 * 角色操作(新增，更新，删除)
 * @param action [add/update/remove]
 * @param data
 *               [add/update 数据结构 {name: string, description: string, listAuthorityId: array} ]
 *               [delete 数据结构 {adminId: int}]
 * @param async/scync [default async]
 */
function adminManagement(action, data, async) {
    var url = null;
    (async === false) ? async = false : async = true;
    if (action === 'add') {
        url = '../admin/addAdmin';
    } else if (action === 'update') {
        url = '../admin/updateAdmin';
    } else {
        url = '/news/jokeMessage/deleteJokeMsg';
    }

    $.ajaxSetup({cache:false});
    return $.ajax({
        type: "POST",
        url: url,
        data: data,
        dataType: 'json',
        async: async,
        beforeSend: function (request) {
            request.setRequestHeader("Authorization", localStorage.token);
        },
        success: function (resb) {
            alert(resb.message);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            // console.log(XMLHttpRequest, textStatus, errorThrown);
            alert(textStatus);
        }
    });
}


/**
 * 查询表单提交
 */
$("#dataSearch").click(function () {
    jokeQuery();
});

/**
 * 新增模态框显示
 */
// $("#addModal").on('show.bs.modal', function () {
//     $(this).find('input[type=password]').val("");
//     $(this).find('input[type=text]').val("");
//     // $(this).find('select ').val("");
// });

/**
 * 删除模态框显示
 */
$("#deleteModal").on('show.bs.modal', function () {
    // var name = $("#report_table").bootstrapTable('getSelections')[0].name,
    var html = '你确定要删除?';
    $(this).find('div.modal-body').empty().append(html);
});

/**
 * 举报原因模态框显示
 */
$("#reportModal").on('show.bs.modal', function () {
    console.log("2")
    // var name = $("#report_table").bootstrapTable('getSelections')[0].name,
    //     html = '你确定要删除管理人员: <span>' + name + '</span>?';
    // $(this).find('div.modal-body').empty().append(html);
    getReason($("#report_table").bootstrapTable('getSelections')[0].forumMsgId);
});

$(document).on('click','.spanIcons',function(){
    $('#inputStation').val("");
    if($('#inputStation').val() ==""){
        $('.spanIcons').removeClass('glyphicon glyphicon-remove');
    }
});
$("#inputStation").keyup(function(){
    if($('#inputStation').val() !=""){
        $('.spanIcons').addClass('glyphicon glyphicon-remove');
    }
    if($('#inputStation').val() ==""){
        $('.spanIcons').removeClass('glyphicon glyphicon-remove');
    }
})

/**
 * 更新模态框显示
 */
$("#updateModal").on('show.bs.modal', function () {
    var $that = $(this),
        $inputs = $that.find("input[type=text]"),
        $belongId = $(this).find('select[name="belongId"]');
    tableData = $("#joke_table").bootstrapTable("getSelections")[0],
        roleAuth = {};

    var $belongId = $(this).find('select[name="belongId"]');
    var $adminState = $(this).find('select[name="adminState"]');
    // 设置ID,姓名,帐号,电话,年龄

    $inputs[0].value = tableData.adminId;
    $inputs[1].value = tableData.name;
    $inputs[2].value = tableData.account;
    $belongId.val(tableData.belongId);
    $adminState.val(tableData.adminState);
    //   $inputs[5].value = tableData.gender;


    $that.find("[name='adminRoles']").prop("checked", false);
    $.each(tableData.roles, function (i, value) {
        $that.find("input[name='adminRoles'][value='" + value.roleId + "']").prop('checked', true);
    });
    //$inputs[5].value = tableData.gender.value;
    //$that.find("input[type=radio]").removeAttr("checked");
    //$that.find("input[type=radio]").attr("checked",false);
    $that.find("input[type=radio]:checked").prop("checked", false);
    if (tableData.gender != null) {
        $that.find("input[type=radio][value='" + tableData.gender + "']").prop("checked", true);
    }
    $('#updateModal').modal('hide');

});

var obj = $("#addForm").validationEngine({

    promptPosition: "centerRight",
    autoPositionUpdate: true,
    validationEventTrigger:'blur',
    //binded:true,
    showOneMessage:true

});
/*if(!obj){
 return false;
 };*/
/**
 * 新增,更新,删除角色表单提交
 */
// $("#addForm,#updateForm,#deleteForm").submit(function () {
$("button[name=submit]").click(function () {
    var type = $(this).data("type"),
        $modal = $("#" + type + "Modal"),
        $inputs = $modal.find('input[type="text"]'),
        $pass = $modal.find('input[name="password"]'),
        $conPass = $modal.find('input[name="confirmPassword"]'),
        tableData = $("#joke_table").bootstrapTable("getSelections")[0],
        data = null,
        adminRoles = [],
        $belongId = $modal.find('select[name="belongId"]'),
        $adminStates = $modal.find('select[name="adminState"]'),
        $checks = $modal.find('input[name="adminRoles"]'),
        $radios = $modal.find('input:radio[name="gender"]:checked'),
        $that = $(this);

    // 模式选择,设置不同的data和url
    if (type === 'delete') {
        data = {
            'jokeMsgId': tableData.jokeMsgId
        };
    } else if (type === 'add') {
        var obj = jQuery("#addForm").validationEngine('validate', {

            promptPosition: "centerRight",
            autoPositionUpdate: true,
            validationEventTrigger:'blur',
            binded:true,
            showOneMessage:true
        });
        if (!obj) {
            return false;
        }
        /*  $checks.each(function (i, n) {
         adminRoles.push(n.value);
         });*/
        $modal.find("input[name='adminRoles']:checked").each(function (i, n) {
            adminRoles.push(n.value);
        });
        data = {
            'name': $inputs[0].value.trim(),
            'password': $pass.val().trim(),
            'account': $inputs[1].value,
            'belongId': $belongId.val(),
            'roleId': adminRoles,
            'gender': $radios.val(),
            'adminState': $adminStates.val()
        };
    } else if (type === 'update') {
        $modal.find("input[name='adminRoles']:checked").each(function (i, n) {
            adminRoles.push(n.value);
        });
        data = {
            'adminId': $inputs[0].value,
            'name': $inputs[1].value.trim(),
            'account': $inputs[2].value.trim(),
            'belongId': $belongId.val().trim(),
            'roleId': adminRoles,
            'gender': $radios.val(),
            'adminState': $adminStates.val()
        };
        // data['adminId'] = tableData.adminId;
    }

    // $('#addModal').modal('hide');
    // $('#updateModal').modal('hide');
    // $('#deleteModal').modal('hide');
    $modal.modal('hide');
    // 完成ajax后刷新表格数据
    adminManagement(type, data).done(function () {
        $("#joke_table").bootstrapTable("refresh");
        $("button[data-target='#updateModal'], button[data-target='#deleteModal']").attr("disabled", 'true');
        $that.parents('.modal-content').find('form')[0].reset();
    });

    // 阻止表格冒泡事件
    return false;
});
